package com.ace.token.common.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 操作键值对
 * @Author
 * @Date 2018年07月04日 下午5:17
 */
@Component
public class RedisValue extends RedisOperation{

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    /**
     * 获取对象
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T>T get(String key,Class<T> clazz){
        Object object = valueOperations.get(key);
        return object!=null?(T)object:null ;
    }


    /**
     * 模糊查询
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T>List<T> getFuzzy(String key, Class<T> clazz){
        StringBuffer stringBuffer = new StringBuffer("*").append(key).append("*");
        Set<String> keys = selectKeys(stringBuffer.toString());
        if (keys.isEmpty()){
            return null;
        }
        List<Object> list = valueOperations.multiGet(keys);
        return (List<T>)list;
    }


    /**
     * 添加对象
     * @param key
     * @param value
     */
    public void add(String key,Object value){
        valueOperations.set(key,value);
    }


    /**
     * 添加对象并设置超时时间,单位秒
     * @param key
     * @param value
     * @param time
     */
   public void add(String key,Object value,Long time){
       valueOperations.set(key,value,time,TimeUnit.SECONDS);

   }


}
